package org.sang.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.sql.SQLException;

@Configuration
public class DataSourceConfig {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);

    @Resource
    private DruidDatasourceProperties datasourceProperties;

    @Bean(initMethod = "init", destroyMethod = "close")
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUseUnfairLock(datasourceProperties.isUseUnfairLock());
        dataSource.setUrl(datasourceProperties.getUrl());
        dataSource.setUsername(datasourceProperties.getUsername());
        dataSource.setPassword(datasourceProperties.getPassword());
        dataSource.setConnectionProperties(datasourceProperties.getConnectProperties());
        dataSource.setKeepAlive(datasourceProperties.isKeepAlive());
        dataSource.setDriverClassName(datasourceProperties.getDriverClassName());
        dataSource.setFailFast(datasourceProperties.isFailFast());
        dataSource.setValidationQuery(datasourceProperties.getValidationQuery());
        dataSource.setTestWhileIdle(datasourceProperties.isTestWhileIdle());
        dataSource.setTimeBetweenEvictionRunsMillis(datasourceProperties.getTimeBetweenEvictionRunsMillis());
        dataSource.setMaxWait(datasourceProperties.getMaxWait());
        dataSource.setPhyTimeoutMillis(datasourceProperties.getPhyTimeoutMillis());
        dataSource.setMinEvictableIdleTimeMillis(datasourceProperties.getMinEvictableIdleTimeMillis());
        dataSource.setMaxEvictableIdleTimeMillis(datasourceProperties.getMaxEvictableIdleTimeMillis());
        dataSource.setInitExceptionThrow(true);
        try {
            dataSource.setFilters(datasourceProperties.getFilters());
        } catch (SQLException e) {
            logger.error("create DruidDataSource bean failed", e);
            throw new BeanCreationException("create DruidDataSource bean failed, caused by " + e.getMessage());
        }
        return dataSource;
    }

}
